package app

import (
	"fmt"
	"strings"

	"git.sr.ht/~mil/mobsql/logger"
	"git.sr.ht/~mil/mobsql/utilfuncs"
)

// SourcesetPurge removes from the database the given sourceset
func SourcesetPurge(m *MDB, sourceset []int) (*SourcesetOpResult, error) {
	logger.Infof("Running SourcesetPurge against %d sources", len(sourceset))
	defer logger.Infof("Running SourcesetPurge against %d sources ok", len(sourceset))

	var (
		inContext        = strings.Join(utilfuncs.ArrayWithValue(len(sourceset), "?"), ",")
		deleteStatements = []string{
			fmt.Sprintf("delete from _mobsql where source in (%s)", inContext),
		}
		args = sourceset
	)
	for _, table := range m.Schema.TablesGTFS {
		deleteStatements = append(
			deleteStatements,
			fmt.Sprintf("delete from %s where source in (%s)", table.TableSpec.Table, inContext),
		)
		// Note: 32766 is max size of args (TODO: pass as single arg?)
		args = append(args, sourceset...)
	}
	if _, err := m.DB.Exec(
		strings.Join(deleteStatements, ";\n"),
		utilfuncs.Anyify(args)...,
	); err != nil {
		return nil, err
	} else {
		return &SourcesetOpResult{
			Operation: "purge",
			Success:   true,
			Mdbids:    sourceset,
		}, nil
	}
}
